package config

import (
	"encoding/xml"
	"io/ioutil"
	"log"
	"github.com/astaxie/beego/logs"
	"errors"
	"os"
	"os/exec"
	"strings"
	"strconv"
	"github.com/astaxie/beego"
	"xiaoercaidan/publicResources/utils"
)

var config Config

func init() {
	config = getConfigXml()

}

func InitConfig(systemName string, initBaseHost bool) {

	if err, host, port, runmode := getConfig(systemName); err == nil {

		if p, err := strconv.ParseInt(*port, 10, 32); err == nil {
			beego.BConfig.Listen.HTTPPort = int(p)
		}

		beego.AppConfig.Set("httphost", *host)

		path := GetCurrentPath() + "logs/"

		if exist, _ := utils.PathExists(path); !exist {

			os.Mkdir(path, os.ModePerm)

		}

		filePath := `{"filename":"` + path + systemName + ".log" + `"}`

		logs.SetLogger(logs.AdapterFile, filePath)

		beego.AppConfig.Set("runmode", *runmode)

	}

	if db, err := GetDBConfig(); err == nil {
		beego.AppConfig.Set("db.host", db.Host)
		beego.AppConfig.Set("db.port", db.Port)
		beego.AppConfig.Set("db.user", db.User)
		beego.AppConfig.Set("db.name", db.Name)
		beego.AppConfig.Set("db.pass", db.Pass)
	}

	if initBaseHost {
		if err, host, port, _ := getConfig("baseApi"); err == nil {

			beego.AppConfig.Set("baseport", *port)
			beego.AppConfig.Set("basehost", *host)

		}
	}


	if systemName=="socketCenter" {
		if err, _, port, _ := getConfig("socketService"); err == nil {
			beego.AppConfig.Set("socketport", *port)

		}
	}


}

func getConfig(serviceName string) (error, *string, *string, *string) {

	var host string
	var port string
	var runmode string

	if (&config != nil) {

		runmode = config.Global.RunMode

		for i := 0; i < len(config.Service); i++ {

			if config.Service[i].Name == serviceName {

				host = config.Service[i].Host

				port = config.Service[i].Port

			}
		}

		return nil, &host, &port, &runmode
	} else {
		logs.Error("配置文件错误")
		return errors.New("配置文件错误"), &host, &port, &runmode
	}

}

func GetDBConfig() (*Database, error) {

	if (&config != nil) {
		return &config.Database, nil
	} else {
		logs.Error("配置文件错误")
		return nil, errors.New("配置文件错误")
	}

}

type Config struct {
	Root     xml.Name         `xml:"config"`
	Service  []Service `xml:"service"`
	Global   Global `xml:"global"`
	Database Database `xml:"database"`
}

type Global struct {
	RunMode string    `xml:"runmode"`
}

type Log struct {
	Path string    `xml:"path"`
}

type Database struct {
	Port string    `xml:"port"`

	Host string    `xml:"host"`

	User string    `xml:"user"`

	Pass string    `xml:"pass"`

	Name string    `xml:"name"`
}

type Service struct {
	Name string   `xml:"name,attr"`

	Port string    `xml:"port"`

	Host string    `xml:"host"`
}

func getConfigXml() Config {

	var path string


	//if beego.BConfig.RunMode == "dev" {
	//	path = "../publicResources/config/"
	//} else {
	//	path = GetCurrentPath()
	//}

	path = GetCurrentPath()

	content, err := ioutil.ReadFile(path + "config.xml")

	if err != nil {
		log.Fatal(err)
	}

	var config Config

	err = xml.Unmarshal(content, &config)

	if err != nil {
		log.Fatal(err)
	}

	return config

}

func GetCurrentPath() string {
	s, _ := exec.LookPath(os.Args[0])
	i := strings.LastIndex(s, "\\")
	path := string(s[0 : i + 1])

	path = strings.Replace(path, "\\", "/", -1)

	return path
}
